package com.fengzai.demo.config;

import com.fengzai.netty.common.callback.HandlerProcessor;
import com.fengzai.netty.websocket.WebsocketServer;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @PACKAGE_NAME: com.fengzai.demo.config
 * @author: rhf
 * @ProjectName: netty
 * @DATE: 2021/10/27
 **/
@Configuration
public class WebsocketConfiguration {
    /**
     * 服务端ip
     */
    private Integer servicePort = 10005;

    @Bean(destroyMethod = "stop")
    public WebsocketServer websocketServer() {
        HandlerProcessor<TextWebSocketFrame, String> handlerProcessor = new HandlerProcessor<TextWebSocketFrame, String>() {
            @Override
            public String process(TextWebSocketFrame msg) throws IOException {
                return msg.content().toString(StandardCharsets.UTF_8);
            }
        };
        WebsocketServer websocketServer = new WebsocketServer(handlerProcessor);
        new Thread() {
            @Override
            public void run() {
                websocketServer.run(servicePort);
            }
        }.start();
        return websocketServer;
    }
}
